var express = require('express');
var router = express.Router();
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync(__dirname + '/../data/db.json');
const db = low(adapter);
const moment = require('moment');

const shortid = require('shortid');

const AccountsModel = require('../models/AccountsModel');
const e = require("express");
const mongoose = require("mongoose");
//账本列表
router.get('/accounts',(req,res,next) => {
  AccountsModel.find().sort({time:-1}).exec((error,data) => {
    if (error) {
      res.status(500).send('获取失败');
      return;
    }
    res.render('index',{accounts:data,moment:moment});
  });

});

//添加账本
router.get('/accounts/add',(req,res,next) => {
  res.render('create');
})

router.post('/accounts',(req, res) => {
  let id = shortid.generate();
  AccountsModel.create({
      ...req.body,
      time: moment(req.body.time).toDate()
  }, (error,data) => {
    if (error) {
      res.status(500).send('添加失败~~~');
      return;
    }
    res.render('success',{msg:'添加成功~~~',url:'/accounts'});
  })

})


router.get('/accounts/:id' ,(req, res) => {
  let id = req.params.id;
  AccountsModel.deleteOne({_id:id}).exec((error) => {
    if (error) {
      res.status(500).send("删除失败");
      return;
    }
    res.render('success',{msg:'删除成功~~~',url:'/accounts'})
  });

})

module.exports = router;
